// pages/orders/designPlanDetail/index.js
const app = getApp()
const router = require('../../../utils/router.js')
const api = require('../../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    orderId: null,
    designPlan: null
  },
  tapNavigateToUrl({ currentTarget }) {
    router.push(currentTarget.dataset.url)
  },
  getDesignPlan() {
    return new Promise((resolve, reject) => {
      api._get('/User/Design/Plan', {
        designInfoID: this.data.orderId
      }).then(res => {
        if (res.Code === 100000) {
          this.setData({
            designPlan: res.Data
          })
          resolve(res.Data)
        }
      })
    })
  },
  /**
   * 生成订单
   */
  createOrder() {
    api._post('/Pay/Order/Create', {
      itemID: this.data.orderId,
      orderType: 2
    }, {
        loadingText: '正在生成订单'
      }).then(res => {
        if (res.Code === 100000) {
          this.payOrder(res.Data).then(() => {
            wx.showToast({
              title: '支付成功',
            })
            wx.redirectTo({
              url: `/pages/orders/detail/index?orderId=${this.data.orderId}`,
            })
          })
        }
      })
  },
  payOrder (object) {
    const that = this
    return new Promise(resolve => {
      if (object.Price === 0) {
        resolve()
      } else {
        wx.requestPayment({
          timeStamp: object.timeStamp,
          nonceStr: object.nonceStr,
          package: object.package,
          signType: object.signType,
          paySign: object.paySign,
          success() {
            resolve()
          },
          fail() {
            console.log('支付失败')
          },
          complete(res) {
            if (res.errMsg === 'requestPayment:fail cancel') {
              wx.showToast({
                icon: 'none',
                title: '用户取消支付'
              })
            }
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ orderId }) {
    this.setData({
      orderId: orderId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDesignPlan()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})